<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 输入框区域 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入内容" clearable @clear="getUserList" v-model="userInfo.query">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userList" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#409EFF"
              inactive-color="#909399"
              @change="switchState(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <!-- 用户操作区域 -->
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="reviseUserIfo(scope.row.id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="delUser(scope.row.id)"></el-button>
            <el-tooltip class="item" effect="dark" content="用户管理" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 选择分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="userInfo.pagenum"
        :page-sizes="[1, 3, 5, 10]"
        :page-size="userInfo.pagenum"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户弹出层 -->
    <el-dialog title="添加新用户" :visible.sync="dialogVisible" width="70%" @close="dialogClose">
      <!-- 用户添加表单 -->
      <el-form ref="form" :model="form" label-width="70px" :rules="rulesForm">
        <el-form-item label="姓名" prop="username">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="username">
          <el-input v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="form.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户弹出层 -->
    <el-dialog title="修改信息" :visible.sync="reviseVisible" width="50%" @close="edDialogClose">
      <!-- 用户修改表单 -->
      <el-form ref="form" :model="reviseUserForm" label-width="70px" :rules="rulesForm">
        <el-form-item label="姓名">
          <el-input v-model="reviseUserForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="reviseUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="reviseUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="reviseVisible = false">取 消</el-button>
        <el-button type="primary" @click="reviseBtn">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色的弹出层 -->
    <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" @close="setRoleDialogClosed" width="50%">
      <div>
        <p>当前的用户:{{ userForm.username }}</p>
        <p>当前的角色:{{ userForm.role_name }}</p>
        <el-select v-model="selectRoleId" placeholder="请选择">
          <el-option v-for="item in roleList" :key="item.id" :label="item.roleDesc" :value="item.id"> </el-option>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 自定义校验规则
    const checkEmail = (rule, val, cb) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(val)) {
        cb()
      }
      cb(new Error('请输入正确的邮箱'))
    }
    const checkMobile = (rule, val, cb) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(val)) {
        cb()
      }
      cb(new Error('请输入正确的手机号码'))
    }
    return {
      userList: [],
      userInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      total: 0,
      // 用户添加弹出层
      dialogVisible: false,
      // 用户修改弹出层
      reviseVisible: false,
      // 添加用户的表单
      form: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 修改用户的表单
      reviseUserForm: {
        id: '',
        username: '',
        email: '',
        mobile: ''
      },
      rulesForm: {
        username: [
          { required: true, message: '请输入用户姓名', trigger: 'blur' },
          { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入用户密码', trigger: 'blur' },
          { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入用户邮箱', trigger: 'blur' },
          { min: 8, max: 15, message: '长度在 8 到 15 个字符', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入用户电话', trigger: 'blur' },
          { min: 11, max: 11, message: '长度不少于 11 个字符', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      setRoleDialogVisible: false,
      // 用户信息
      userForm: {},
      // 所有角色列表
      roleList: [],
      // 选中的角色 ID 值
      selectRoleId: ''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.userInfo
      })
      if (res.meta.status !== 200) return this.$message.error('获取用户列表失败')
      this.total = res.data.total
      this.userList = res.data.users
    },
    // 监听 pageSize 改变的事件
    handleSizeChange(newSize) {
      this.userInfo.pagesize = newSize
      this.getUserList()
    },
    // 监听 页码值 改变事件
    handleCurrentChange(newPage) {
      this.userInfo.pagenum = newPage
      this.getUserList()
    },
    // 监听 switch 开关状态
    async switchState(userInfo) {
      const { data: res } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('更改用户状态失败!')
      }
      this.$message.success('更换用户状态成功!')
    },
    // 监听弹出层关闭并且清空表单数据
    dialogClose() {
      this.$refs.form.resetFields()
    },
    addUserInfo() {
      this.$refs.form.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post('users', this.form)
        if (res.meta.status !== 201) return this.$message.error('添加用户失败')
        this.$message.success('添加用户成功')
        this.dialogVisible = false
        this.getUserList()
      })
    },
    // 用户点击修改图标
    async reviseUserIfo(id) {
      this.reviseVisible = true
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) return
      this.reviseUserForm = res.data
    },
    async delUser(id) {
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)
      if (confirmResult !== 'confirm') return
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除用户失败!')
      this.$message.success('删除用户成功!')
      this.getUserList()
    },
    edDialogClose() {
      this.$refs.form.resetFields()
    },
    // 修改后点击确认的处理函数
    reviseBtn() {
      this.$refs.form.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put('users/' + this.reviseUserForm.id, {
          email: this.reviseUserForm.email,
          mobile: this.reviseUserForm.mobile
        })
        if (res.meta.status !== 200) return this.$message.error('修改用户信息失败!')
        this.reviseVisible = false
        this.getUserList()
        this.$message.success('修改用户成功!')
      })
    },
    async setRole(userInfo) {
      this.userForm = userInfo
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败!')
      this.roleList = res.data
      this.setRoleDialogVisible = true
    },
    async saveRoleInfo() {
      if (!this.selectRoleId) return this.$message.error('请选择分配的角色!')
      const { data: res } = await this.$http.put(`users/${this.userForm.id}/role`, { rid: this.selectRoleId })
      if (res.meta.status !== 200) return this.$message.error('分配角色失败!')
      this.$message.success('分配角色成功')
      this.setRoleDialogVisible = false
      this.getUserList()
    },
    // 监听 用户管理 窗口关闭
    setRoleDialogClosed() {
      this.selectRoleId = ''
    }
  }
}
</script>

<style></style>
